package com.sinopec.basemodule.dialog

import android.graphics.Point
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.Window
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView
import com.jakewharton.rxbinding3.view.clicks
import com.jelly.thor.maxnumberet.MaxEditTextView
import com.sinopec.basemodule.R
import com.sinopec.basemodule.adapter.*
import com.sinopec.basemodule.api.BaseModuleApi
import com.sinopec.basemodule.http.ExceptionEngine
import com.sinopec.basemodule.http.api.HttpResult
import com.sinopec.basemodule.http.func.HttpResponseFunc
import com.sinopec.basemodule.http.func.ServerResponseFunc
import com.sinopec.basemodule.model.*
import com.sinopec.basemodule.utils.CommonUtils
import com.sinopec.basemodule.utils.ToastUtils
import com.sinopec.basemodule.utils.kotlin.parseDouble
import com.sinopec.basemodule.utils.kotlin.parseInt
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.choose_pre_sort_order_popupwindow.*
import java.util.concurrent.TimeUnit

/**
 * @author lwj
 * @ClassName: ChoosePreSortByDialog
 * @Description: 分拣-预分拣弹窗
 */
class ChoosePreSortDialog : DFBase() {
    //列表集合
    val models = arrayListOf<SortOrderSkuRequestModel>()
    private var adapter: CommonAdapter<SortOrderSkuRequestModel>? = null

    companion object {
        @JvmStatic
        fun newInstance(
            model: SortingToBeSortedChildModel,
            listProductTypeName: ArrayList<ProductBusinessNameItemModel>
        ): ChoosePreSortDialog {
            val args = Bundle()
            args.putParcelable("model", model)
            args.putParcelableArrayList("listProductTypeName", listProductTypeName)
            val fragment = ChoosePreSortDialog()
            fragment.arguments = args
            return fragment
        }
    }

    /**
     * 按单分拣列表model
     */
    private val mModel by lazy {
        arguments?.getParcelable("model") ?: SortingToBeSortedChildModel()
    }

    /**
     * 业务类型集合
     */
    private val mListProductTypeName by lazy {
        arguments?.getParcelableArrayList("listProductTypeName")
            ?: ArrayList<ProductBusinessNameItemModel?>()
    }

    override fun setOutClick() {
        super.setOutClick()
        //外部点击事件
        isCancelable = false
        dialog?.setCanceledOnTouchOutside(false)
    }

    interface Callback {
        /**
         * 保存
         */
        fun onSave(model: PreSortOrderDialogRequestModel)

        /**
         * 保存并扫码
         */
        fun onSaveScan(model: PreSortOrderDialogRequestModel)
    }

    private var mCallback: Callback? = null

    fun setCallback(callback: Callback) {
        mCallback = callback
    }

    private fun initEvent() {
        /**
         * 关闭
         */
        cd.add(tv_exit.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                dismiss()
            })

        /**
         * 保存
         */
        cd.add(tv_save.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                models.forEach {
                    //业务类型必选
                    if (it.chooseProductBusinessNameItemModel?.productBusinessId.isNullOrEmpty()) {
                        ToastUtils.showToast("请选择业务类型！")
                        return@subscribe
                    }

                    //规格必选
//                    if (it.chooseProductSpecModel?.productSpecId.isNullOrEmpty()) {
//                        ToastUtils.showToast("请选择规格！")
//                        return@subscribe
//                    }

                    //每一个item的预分拣、编码丢失、二维码破损数量必须填一个
                    val total: Int =
                        it.presortedCount.parseInt() + it.codeLossCount.parseInt() + it.qrBrokenCount.parseInt()
                    if (total <= 0) {
                        ToastUtils.showToast("存在SKU预分拣数为空！")
                        return@subscribe
                    }
                }

                //预分拣：总分拣数<=待分拣数时才能保存
                if (tv_waitSortCount.text.toString().parseInt() < tv_totalSortCount.text.toString()
                        .parseInt()
                ) {
                    ToastUtils.showToast("总分拣数小于等于待分拣数时才能保存!")
                    return@subscribe
                }

                val requestModel = PreSortOrderDialogRequestModel()
                //requestModel.stockInId = mModel.stockInId
                //分拣-按单分拣预分拣弹窗保存接口入参

                val skuRequestDtos = models.mapTo(ArrayList()) { e ->
                    PreSortOrderDialogRequestItem().also {
                        //大类id
                        it.productCategoryId = mModel.productCategoryId
                        //业务类型id
                        it.productBusinessId =
                            e.chooseProductBusinessNameItemModel?.productBusinessId
                        //规格id
                        it.productSpecId = e.chooseProductSpecModel?.productSpecId
                        //预分拣数量
                        it.presortedCount = e.presortedCount.parseInt().toString()
                        //编码丢失数量
                        it.codeLossCount = e.codeLossCount.parseInt().toString()
                        //二维码破损数量
                        it.qrBrokenCount = e.qrBrokenCount.parseInt().toString()
                    }
                }
                requestModel.skuRequestDtos = skuRequestDtos
                mCallback?.onSave(requestModel)
            })

        /**
         * 保存并扫码
         */
        cd.add(tv_scan.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (models.size > 1) {
                    ToastUtils.showToast("只允许存在一个填写栏！")
                    return@subscribe
                }

                models.forEach {
                    //业务类型必选
                    if (it.chooseProductBusinessNameItemModel?.productBusinessId.isNullOrEmpty()) {
                        ToastUtils.showToast("请选择业务类型！")
                        return@subscribe
                    }

                    //规格必选
//                    if (it.chooseProductSpecModel?.productSpecId.isNullOrEmpty()) {
//                        ToastUtils.showToast("请选择规格！")
//                        return@subscribe
//                    }

                    //每一个item的预分拣、编码丢失、二维码破损数量必须填一个
                    val total: Int =
                        it.presortedCount.parseInt() + it.codeLossCount.parseInt() + it.qrBrokenCount.parseInt()
                    if (total <= 0) {
                        ToastUtils.showToast("存在SKU预分拣数为空！")
                        return@subscribe
                    }
                }

                val countTimes =
                    models.groupBy { it.chooseProductBusinessNameItemModel?.productBusinessId }.size
                if (countTimes > 1) {
                    ll_tips.visibility = View.VISIBLE
                    return@subscribe
                } else {
                    ll_tips.visibility = View.GONE
                }

                //预分拣：总分拣数<=待分拣数时才能保存
                if (tv_waitSortCount.text.toString().parseInt() < tv_totalSortCount.text.toString()
                        .parseInt()
                ) {
                    ToastUtils.showToast("总分拣数小于等于待分拣数时才能保存!")
                    return@subscribe
                }

                val requestModel = PreSortOrderDialogRequestModel()
                //requestModel.stockInId = mModel.stockInId
                //分拣-按单分拣预分拣弹窗保存接口入参

                val skuRequestDtos = models.mapTo(ArrayList()) { e ->
                    PreSortOrderDialogRequestItem().also {
                        //大类id
                        it.productCategoryId = mModel.productCategoryId
                        //业务类型id
                        it.productBusinessId =
                            e.chooseProductBusinessNameItemModel?.productBusinessId
                        //规格id
                        it.productSpecId = e.chooseProductSpecModel?.productSpecId
                        //预分拣数量
                        it.presortedCount = e.presortedCount.parseInt().toString()
                        //编码丢失数量
                        it.codeLossCount = e.codeLossCount.parseInt().toString()
                        //二维码破损数量
                        it.qrBrokenCount = e.qrBrokenCount.parseInt().toString()
                    }
                }
                requestModel.skuRequestDtos = skuRequestDtos
                mCallback?.onSaveScan(requestModel)
            })
    }

    override fun initView(view: View?) {
        initDialog()
        initEvent()
        //入库单号
//        tv_stockInCode.visibility = View.VISIBLE
//        tv_stockInCode.text = mModel.stockInCode?.ifEmpty { "--" }
        //大类
        tv_productCategoryName.text = mModel.productCategoryName.ifEmpty { "--" }
        //待分拣数
        tv_waitSortCount.text = mModel.count
        //总分拣数
        tv_totalSortCount.text = "0"

        adapter = object : CommonAdapter<SortOrderSkuRequestModel>(
            requireActivity(),
            R.layout.pre_sort_order_item_popuwindow,
            models
        ) {
            override fun convert(
                holder: CustomViewHolder,
                sortOrderSkuRequestModel: SortOrderSkuRequestModel,
                position: Int
            ) {
                val itemView = holder.itemView

                /**
                 * 规格spinner
                 */
                val ll_spec = holder.getView<LinearLayout>(R.id.ll_spec)
                val spinner_spec = holder.getView<Spinner>(R.id.spinner_spec)
                val tv_spec = holder.getView<TextView>(R.id.tv_spec)
                val adapterSpec = ProductSpecSpinnerAdapter()
                tv_spec.text = sortOrderSkuRequestModel.chooseProductSpecModel?.productSpecName
                spinner_spec.adapter = adapterSpec
                adapterSpec.addData(sortOrderSkuRequestModel.listSpec)
                adapterSpec.bindSpinner(spinner_spec, ll_spec) { ProductSpecModel, isFirst ->
                    if (!isFirst) {
                        tv_spec.text = ProductSpecModel?.productSpecName
                        models[holder.bindingAdapterPosition].chooseProductSpecModel = ProductSpecModel
                        adapter?.notifyItemChanged(holder.bindingAdapterPosition)
                    }
                }

                /**
                 * 业务类型spinner
                 */
                val ll_productTypeName = holder.getView<LinearLayout>(R.id.ll_productTypeName)
                val spinner_productTypeName = holder.getView<Spinner>(R.id.spinner_productTypeName)
                val tv_productTypeName = holder.getView<TextView>(R.id.tv_productTypeName)
                val adapterProductTypeName = ProductNameSpinnerAdapter()
                tv_productTypeName.text =
                    sortOrderSkuRequestModel.chooseProductBusinessNameItemModel?.productBusinessName
                spinner_productTypeName.adapter = adapterProductTypeName
                adapterProductTypeName.addData(sortOrderSkuRequestModel.listProductTypeName)
                adapterProductTypeName.bindSpinner(
                    spinner_productTypeName,
                    ll_productTypeName
                ) { productBusinessNameItemModel, isFirst ->
                    if (!isFirst) {
                        tv_productTypeName.text = productBusinessNameItemModel?.productBusinessName
                        models[holder.bindingAdapterPosition].chooseProductBusinessNameItemModel =
                            productBusinessNameItemModel
                        //选择了业务类型，把对应下标的规格重置
//                        tv_spec.text = ""
//                        models[holder.bindingAdapterPosition].chooseProductSpecModel = null
                        adapter?.notifyItemChanged(holder.bindingAdapterPosition)

                        //按单-预分拣弹窗下拉规格(网络请求)
//                        getNetSortOrderProductSpecList(
//                            holder.bindingAdapterPosition,
//                            mModel.productCategoryId ?: "",
//                            productBusinessNameItemModel?.productBusinessId ?: ""
//                        )
                    }
                }
                //预分拣数
                val et_presortedCount = holder.getView<MaxEditTextView>(R.id.et_presortedCount)
                et_presortedCount.setText(sortOrderSkuRequestModel.presortedCount)
                et_presortedCount.setModule(0, mModel.count.parseDouble()) {
                    models[holder.bindingAdapterPosition].presortedCount = it
                    //计算总分拣数（所有item的预分拣数+编码丢失数+二维码破损数）
                    countTotalSortCount()
                }

                //编码丢失
                val et_codeLossCount = holder.getView<MaxEditTextView>(R.id.et_codeLossCount)
                et_codeLossCount.setText(sortOrderSkuRequestModel.codeLossCount)
                et_codeLossCount.setModule(0, mModel.count.parseDouble()) {
//                    if(it.parseDouble() == 0.0){
//                        et_codeLossCount.setText("")
//                    }
                    models[holder.bindingAdapterPosition].codeLossCount = it
                    //计算总分拣数（所有item的预分拣数+编码丢失数+二维码破损数）
                    countTotalSortCount()
                }

                //二维码破损
                val et_qrBrokenCount = holder.getView<MaxEditTextView>(R.id.et_qrBrokenCount)
                et_qrBrokenCount.setText(sortOrderSkuRequestModel.qrBrokenCount)
                et_qrBrokenCount.setModule(0, mModel.count.parseDouble()) {
//                    if(it.parseDouble() == 0.0){
//                        et_qrBrokenCount.setText("")
//                    }
                    models[holder.bindingAdapterPosition].qrBrokenCount = it
                    //计算总分拣数（所有item的预分拣数+编码丢失数+二维码破损数）
                    countTotalSortCount()
                }

                //增加item
                val iv_add = holder.getView<ImageView>(R.id.iv_add)
                //删除item
                val iv_delete = holder.getView<ImageView>(R.id.iv_delete)

                if (datas.size == 1) {
                    iv_delete.visibility = View.GONE
                } else {
                    iv_delete.visibility = View.VISIBLE
                }

                /**
                 * 移除item
                 */
                iv_delete.setOnClickListener {
//                    (adapter as CommonAdapter<TaskTypeModel>).notifyItemRemoved(position)
//                    (adapter as CommonAdapter<TaskTypeModel>).notifyItemRangeChanged(position, adapter!!.itemCount)
                    models.remove(sortOrderSkuRequestModel)
                    //计算总分拣数（所有item的预分拣数+编码丢失数+二维码破损数）
                    countTotalSortCount()
                    adapter?.notifyItemRemoved(holder.bindingAdapterPosition)
                    if(models.size > 0){
                        adapter?.notifyItemChanged(0)
                    }
                }

                /**
                 * 增加item
                 */
                iv_add.setOnClickListener {
                    addItemModel()
                }
            }
        }
        rv_list.adapter = adapter
        //默认新增一个item
        addItemModel()
    }

    override fun setDialogParams(window: Window) {
        val point = Point()
        window.windowManager.defaultDisplay.getSize(point)

        //设置宽度百分比
        //#第一种
        //window.setLayout((int) (point.x * 0.5), ViewGroup.LayoutParams.WRAP_CONTENT);
        val layoutParams = window.attributes
        //#第二种
        layoutParams.width = (point.x * 0.8).toInt()
        layoutParams.height = (point.y * 0.8).toInt()
        //layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
        //设置dialog位置
        layoutParams.gravity = Gravity.CENTER
        //设置dialog动画
        //layoutParams.windowAnimations = R.style.anim_popup_dir
        window.attributes = layoutParams
    }

    override fun createView(): Int {
        return R.layout.choose_pre_sort_order_popupwindow
    }

    /**
     * 新增一个item
     */
    private fun addItemModel() {
        if (models.size == 5) {
            ToastUtils.showToast("最多添加5条！")
        } else {
            val model = SortOrderSkuRequestModel()
            model.listProductTypeName = mListProductTypeName
            models.add(model)
            adapter?.notifyItemInserted(models.size - 1)
        }
    }

    /**
     * 计算总分拣数（所有item的预分拣数+编码丢失数+二维码破损数）
     */
    private fun countTotalSortCount() {
        val totalSortCount = models.sumOf {
            it.presortedCount.parseInt() + it.codeLossCount.parseInt() + it.qrBrokenCount.parseInt()
        }

        //总分拣数
        tv_totalSortCount.text = totalSortCount.toString()
    }

    private var progressDialog: TankerProgressDialog? = null

    private fun initDialog() {
        progressDialog = TankerProgressDialog(activity, R.style.CustomDialog)
        progressDialog!!.setCanceledOnTouchOutside(false)
        progressDialog!!.setText("加载中···")
    }

    private fun showProgress() {
        if (!progressDialog?.isShowing!!) {
            progressDialog!!.show()
        }
    }

    private fun dismissProgress() {
        if (progressDialog != null && progressDialog!!.isShowing) {
            progressDialog!!.dismiss()
        }
    }

    /**
     *  按单-预分拣弹窗下拉规格(网络请求)
     */
    private fun getNetSortOrderProductSpecList(
        position: Int,
        productCategoryId: String,
        productBusinessId: String
    ) {
        //显示弹窗
        showProgress()
        //网络获取数据
        val ob: Observable<HttpResult<List<ProductSpecModel?>>> =
            BaseModuleApi.getProductSpecList(productCategoryId, productBusinessId)
        //数据预处理，没有添加缓存
        val subscribe: Disposable =
            ob.map(ServerResponseFunc())
                .onErrorResumeNext(HttpResponseFunc())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    models[position].listSpec = ArrayList(it)
                    adapter?.notifyDataSetChanged()
                    dismissProgress()
                }, { e ->
                    if (e?.message != null) {
                        if (e is ExceptionEngine.ResponseThrowable) {
                            val newE: ExceptionEngine.ResponseThrowable =
                                e as ExceptionEngine.ResponseThrowable
                            CommonUtils.isNeedLogin(activity, newE.code, newE.message)
                        } else {
                            ToastUtils.showToast(e.message)
                        }
                    }
                    dismissProgress()
                });
        cd.add(subscribe)
    }
}